<?php
namespace app\admin\controller;

use app\admin\model\QClass as ClassModel;
use app\admin\model\QuestionData as DataModel;
use app\admin\model\QuestionFormat as FormatModel;
use app\common\controller\Backend;
use app\common\enum\Questionnaire as QEnum;
use app\common\library\Excel;
use app\common\service\Question as QService;
use think\Session;

/**
 *
 *
 * @icon fa fa-circle-o
 */
class QuestionFormat extends Backend
{

    /**
     * QuestionFormat模型对象
     * @var \app\admin\model\QuestionFormat
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\QuestionFormat;

    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $where2 = ['delete_time' => 0];
            if (! in_array(1, $this->auth->getGroupIds())) {
                $where2['uid'] = Session::get('admin')['id'];
            }
            $list = $this->model
                ->where($where)
                ->where($where2)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id', 'name', 'format', 'available', 'show_mode', 'full_mark', 'pass_mark', 'count', 'header_note', 'create_time']);

            }

            $result = ["total" => $list->total(), "rows" => $list->items()];

            return json($result);
        }
        // $data = QService::getQuestionnaireClassList();
        // $mode = QEnum::getMarkShowMode();
        // return $this->fetch('list', ['data' => $data, 'mode' => $mode]);
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post();

            $postData = json_decode($params['postData'], true);
            //format不能为空
            if (! array_key_exists('format', $postData) || ! $postData['format']) {
                // return $this->renderError('没有定义题目！');
                $this->error('没有定义题目！');
            }
            //验证参数是否正确
            if (! ($check = QService::checkAddQuestionnaireParam($postData))) {
                // return $this->renderError('参数错误，请联系开发人员');
                $this->error('参数错误，请联系开发人员');

            } else if (is_string($check)) {
                // $this->renderError($check);
                $this->error($check);

            }

            $classModel = ClassModel::get($postData['q_class_id']);

            if (! $classModel) {

                $this->error('选择的分类不存在，请联系开发人员');

            }
            $qModel                   = new FormatModel();
            $postData['count']        = 0;
            $postData['create_time']  = time();
            $postData['format']       = json_encode($postData['format']);
            $postData['is_automatic'] = $postData['is_automatic'] ? 1 : 0;
            $postData['available']    = $postData['available'] ? 1 : 0;
            $postData['uid']          = Session::get('admin')['id'];
            $qModel->save($postData);

            //问卷分类的模型计数加一
            $classModel->setInc('q_count', 1);

            $this->success();
            die;
        }
        $mode             = QEnum::getMarkShowMode();
        $questionTypeName = QEnum::getQuestionTypeName();
        $class            = (new ClassModel())->getClassName();
        $cate_id          = input('q_class_id', 1);
        return $this->view->fetch('add_2', ['class' => $class, 'mode' => $mode, 'questionTypeName' => $questionTypeName, 'catid' => $cate_id]);
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {

        $params = $this->request->post();
        $row    = $this->model->get($ids);
        if (! $row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (! in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }

        if (! $row) {
            return $this->error('选择的问卷模板不存在，请联系开发人员!');
        }
        if ($this->request->isPost()) {

            $postData = json_decode($params['postData'], true);
            if (! array_key_exists('format', $postData) || ! $postData['format']) {
                // return $this->renderError('没有定义题目！');
                $this->error('没有定义题目！');
            }
            //验证参数是否正确
            if (! ($check = QService::checkAddQuestionnaireParam($postData))) {
                // return $this->renderError('参数错误，请联系开发人员');
                $this->error('参数错误，请联系开发人员');

            } else if (is_string($check)) {
                // $this->renderError($check);
                $this->error($check);

            }
            //如果分类变动要更新q_count
            if ($postData['q_class_id'] != $row['q_class_id']) {
                $classModel = ClassModel::get($row['q_class_id']);
                $classModel->setDec('q_count', 1);

                $classModel = ClassModel::get($postData['q_class_id']);
                $classModel->setInc('q_count', 1);
            }

            $postData['update_time']  = time();
            $postData['format']       = json_encode($postData['format']);
            $postData['is_automatic'] = $postData['is_automatic'] ? 1 : 0;
            $postData['available']    = $postData['available'] ? 1 : 0;
            $this->model->where(['id' => $ids])->update($postData);
            $this->success();
            die;

        }
        $questionTypeName = QEnum::getQuestionTypeName();
        $mode             = QEnum::getMarkShowMode();
        $class            = (new ClassModel())->getClassName();

        return $this->view->fetch('edit', ['class' => $class, 'qModel' => $row, 'mode' => $mode, 'questionTypeName' => $questionTypeName]);

    }
    public function del($ids = "")
    {

        $row = $this->model->get($ids);
        if (! $row) {
            $this->error(__('No Results were found'));
        }
        $this->model->where(['id' => $ids])->update(['delete_time' => time()]);
        $this->success();
    }

    public function delete()
    {
        $ids = input();
        $this->model->where(['id' => ['in', $ids['ids']]])->update(['delete_time' => time()]);
        $this->success();
    }

    public function active()
    {
        $ids = input();

        $this->model->where(['id' => ['in', $ids['ids']]])->update(['available' => 1]);
        $this->success();
    }

    public function disabled()
    {
        $ids = input();
        $this->model->where(['id' => ['in', $ids['ids']]])->update(['available' => 0]);
        $this->success();
    }

    /**
     * 获取问卷模板详情
     */
    public function detail($ids = "")
    {
        $param  = input('param.');
        $qModel = FormatModel::get($ids);
        if (! $qModel) {
            return $this->error('选择的问卷模板不存在，请联系开发人员!');
        }

        $questionTypeName = QEnum::getQuestionTypeName();
        $mode             = QEnum::getMarkShowMode();
        $class            = (new ClassModel())->getClassName();

        return $this->fetch('detail', ['class' => $class, 'mode' => $mode, 'qModel' => $qModel, 'questionTypeName' => $questionTypeName]);

    }

    /**
     * 生成某问卷模板下数据的Excel文件
     */
    public function getQuestionnaireExcelFile($qid, $order = null, $order1 = null)
    {
        $params    = input();
        $formTitle = ['数据id', '用户名',
            // '分数', '回复', '是否已处理', '是否需要用户查看', '是否及格',
            '创建时间'];
        $qModel = FormatModel::get($qid); //格式
        if (! $qModel) {
            $this->error('选择的问卷数据不存在，请联系开发人员');
        }
        $format           = json_decode($qModel['format'], true);
        $questionTypeName = QEnum::getQuestionTypeName();
        foreach ($format as $formatItem) { //处理表头
            if ($formatItem['type'] == 4) {
                foreach ($formatItem['title_list'] as $subTitle) {
                    $formTitle[] = $formatItem['title'] . '-' . $subTitle . '（' . $questionTypeName[$formatItem['type']] . '）';
                }
            } else {
                $formTitle[] = $formatItem['title'] . '（' . $questionTypeName[$formatItem['type']] . '）';
            }
        }
        $questionnaireDoneList = DataModel::where('ftu_child_q_data.qid', '=', $params['qid'])
            ->field('f.name as title,f.full_mark,f.pass_mark,ftu_child_q_data.*,u.nickname')
            ->join('ftu_child_q_format f', 'ftu_child_q_data.qid = f.id', 'left')
            ->join('ftu_user u', 'ftu_child_q_data.uid = u.id', 'left')
                    // ->order('ftu_child_q_data.id desc')
            ->select(); //获取每份问卷
        $formData = [];
        // print_r($questionnaireDoneList);exit;
        foreach ($questionnaireDoneList as $item) { //转义问卷收集的数据
                                                        // $item['create_time']=Date('Y-m-d H:i',$item['create_time']);
            $foo = [
                $item['id'],
                $item['nickname'],
                // $item['mark'],
                // $item['note'],
                // $item['dealt']?'是':'否',
                // $item['viewed']?'是':'否',
                // $item['pass']?'是':'否',
                Date('Y-m-d H:i', strtotime($item['create_time'])),
            ];
            $qData         = DataModel::get($item['id']); //问卷详情
               
            $qData['data'] = json_decode($qData['data'], true);
            // 提取id作为新数组的键
            $qData['data'] = array_column($qData['data'], null, 'id');
 

            foreach ($format as $id => $formatRow) {

                if (isset($qData['data'][$id])) {
                    $data = $qData['data'][$id];
 //dump(['m'=>$data]);
                    switch ($data['type']) {
                        case 5:
                        case 6:
                        case 0:
                            if (isset($format[$id]['option'])) {
                                 
                                if (isset($format[$id]['option'][$data['choice']])) {
                                   
                                    $foo[] = $format[$id]['option'][$data['choice']];
                                }

                            }

                            break;
                        case 1:
                            $bar = '';
                        
                            foreach ($data['choice_list'] as $kk=>$choice) {
//dump(['m'=>implode(',', $data['choice_list'])]);
                                $findex=mb_strpos(implode(',', $data['choice_list']),$kk);
                                if ($findex>-1) {
                                    $bar .= $format[$id]['option'][$kk] . '、';
                  
                                }
                            }
                            $foo[] = mb_substr($bar, 0, -1, 'utf8');
                            break;
                        case 2:
                            $bar = '';
                            $i   = 0;
                            foreach ($format[$id]['text_list'] as $text) {
                                if ($text == '$') {
                                    
                                    if (isset($data['answer_list'][$i])) {
                                        $bar .= '（' . $data['answer_list'][$i] . '）';
                                    }
                                    $i = $i + 1;
                                } else {
                                    $bar .= $text;
                                }
                            }
                            $foo[] = $bar;
                            break;
                        case 3:
                            $foo[] = $data['answer'];
                            break;
                        case 4:
                            foreach ($data['answer_list'] as $aId => $answer) {
                                $foo[] = isset($format[$id]['option'])?$format[$id]['option'][$answer]:$answer;
                            }
                            break;
                    }
                } else {
                    $foo[] = '';
                }

            }
            $formData[] = $foo;
        }

        $xlsName = $qModel['name'] . ' ' . date("Y-m-d", time()); //文件名称
        $keys    = [];
        for ($i = 0; $i < count($formTitle); $i++) {
            $keys[] = $i;
        }
     //dump(['m'=>$formData,'key'=>$keys]);die;
        $Excel = new Excel();
        $Excel->downloadExcel($xlsName, $formData, $formTitle, $keys); // 传递参数
    }

    public function getcode()
    {
        $ids = input('ids');

        $wx = new \app\api\model\Wx();

        $page = 'pages/fill/fills';
        //release trial
        $res = $wx->getUnlimit($ids, $page, 'release');

        if ($res['code'] == '200') {

            $url = 'https://ftuline.astarsw.cn/uploads/code/' . $ids . '_appcode.png';
            FormatModel::where(['id' => $ids])->update(['code_url' => $url]);
            $this->success('', '', ['url' => $url]);
        }
        return $this->error('生成小程序码失败!');
    }

    /**
     * 获取某问卷模板填写情况
     */
    public function getQuestionnaireDoneList()
    {
        $params = input();

        $qModel = FormatModel::get($params['qid']);
        if (! $qModel) {
            return $this->error('选择的问卷模板不存在，请联系开发人员!');
        }
        $list = DataModel::where('ftu_child_q_data.qid', '=', $params['qid'])
            ->field('f.name,f.full_mark,f.pass_mark,ftu_child_q_data.*,u.nickname')
            ->join('ftu_child_q_format f', 'ftu_child_q_data.qid = f.id', 'left')
            ->join('ftu_user u', 'ftu_child_q_data.uid = u.id', 'left')
            ->paginate(20000000);
        foreach ($list as $key => $value) {
            // $list[$key]['create_time2']=Date('Y-m-d H:i',$value['create_time']);
        }

        $classes = [];
        return $this->view->fetch('doneList', compact('list', 'classes'));
    }

    /**
     * 查看
     */
    public function lists()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        $params = input();
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $where2                                      = [];
            $where2                                      = ['available' => 1, 'delete_time' => 0];

            if (! in_array(1, $this->auth->getGroupIds())) {
                $where2['uid'] = Session::get('admin')['id'];
            }

            if (isset($params['name']) && ! empty($params['name'])) {
                $where2['name'] = ['like', '%' . $params['name'] . '%'];
            }

            $list = $this->model
                ->where($where)
                ->where($where2)
                ->field('id,name')
            // ->order($sort, $order)
                ->paginate(15);

            $result = ["total" => $list->total(), "list" => $list->items()];

            return json($result);
        }

    }

    /**
     * 获取问卷数据
     */
    public function getDealQuestionnaireData()
    {
        $params = input();

        $qData = DataModel::get($params['ids']);
        if (! $qData) {
            return $this->error('选择的问卷数据不存在，请联系开发人员!');
        }
        $qModel = FormatModel::get($qData['qid']);
        if (! $qModel) {
            return $this->error('选择的问卷模板不存在，请联系开发人员!');
        }

        $questionTypeName = QEnum::getQuestionTypeName();
        $mode             = QEnum::getMarkShowMode();
        $class            = 'class';
        return $this->view->fetch('dealQuestionnaireData', ['qData' => $qData, 'class' => $class, 'mode' => $mode, 'qModel' => $qModel, 'questionTypeName' => $questionTypeName]);
    }

    /**
     * 处理问卷
     */
    public function dealDoneQuestionnaire($qid, $id)
    {
        $params = input();
        $qModel = FormatModel::get($params['id']);
        if (! $qModel) {
            return $this->error('选择的问卷模板不存在，请联系开发人员!');
        }
        $qData = DataModel::get($params['id']);
        if (! $qData) {
            return $this->error('选择的问卷数据不存在，请联系开发人员!');
        }

        $postData = json_decode($params['postData'], true);
        if (! (bool) $postData['mark'] || ! (int) ($postData['mark'])) {
            return $this->error('请正确填写分数');
        }
        //判断是否超过满分
        if ((int) ($postData['mark']) > $qModel['full_mark']) {
            return $this->error('分数超过了满分了');
        }
        $old_viewed = $qData['viewed'];
        $old_pass   = (bool) $qData['pass'];
        $old_dealt  = (bool) $qData['dealt'];
        //判断是否及格
        $mark = (int) $postData['mark'];
        $pass = null;
        if ($mark >= (int) $qModel['pass_mark']) {
            $pass = 1;
        } else {
            $pass = 0;
        }
        $qData->isUpdate()->save(['note' => $postData['note'], 'mark' => $postData['mark'], 'dealt' => 1, 'viewed' => 0, 'pass' => $pass]);

        return $this->success('操作成功！');

        //原本是未处理的问卷才需要通知

    }
}
